package com.cloud.example.business.flow.controller.depend;

import com.cloud.async.flow.web.client.FlowTemplate;
import com.cloud.async.flow.worker.WorkResult;
import com.cloud.async.flow.wrapper.WorkerWrapper;
import com.cloud.example.business.flow.controller.depend.worker.DeWorker;
import com.cloud.example.business.flow.controller.depend.worker.DeWorker1;
import com.cloud.example.business.flow.controller.depend.worker.DeWorker2;
import com.cloud.example.business.flow.controller.depend.worker.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;

/**
 * 后面请求依赖于前面请求的执行结果
 *
 * @author chengrui
 */
@RequestMapping("/api/flow")
@RestController
public class DependController {

    /**
     * logger
     */
    private final Log logger = LogFactory.getLog(getClass());

    @Autowired
    FlowTemplate flowTemplate;

    @GetMapping("/depend")
    public String depend() throws ExecutionException, InterruptedException {

        DeWorker w = new DeWorker();
        DeWorker1 w1 = new DeWorker1();
        DeWorker2 w2 = new DeWorker2();
        WorkerWrapper<WorkResult<User>, String> workerWrapper2 = new WorkerWrapper.Builder<WorkResult<User>, String>()
                .worker(w2)
                .callback(w2)
                .id("third")
                .build();
        WorkerWrapper<WorkResult<User>, User> workerWrapper1 = new WorkerWrapper.Builder<WorkResult<User>, User>()
                .worker(w1)
                .callback(w1)
                .id("second")
                .next(workerWrapper2)
                .build(true);

        WorkerWrapper<String, User> workerWrapper = new WorkerWrapper.Builder<String, User>()
                .worker(w)
                .param("workerWrapper params")
                .id("first")
                .next(workerWrapper1, true)
                .callback(w)
                .build();
        System.out.println(Thread.currentThread().getName());
        //尚未执行，先取得结果的引用，作为下一个任务的入参。
        //直接在worker的action里自行根据id获取即可.
        // 参考：com.cloud.example.business.flow.controller.depend.DependNewController.dependNew
        WorkResult<User> result = workerWrapper.getWorkResult();
        WorkResult<User> result1 = workerWrapper1.getWorkResult();
        workerWrapper1.setParam(result);
        workerWrapper2.setParam(result1);
        //do flow
        flowTemplate.startWork(3500, workerWrapper);

//        logger.info("------end------");
//        logger.info("worker0 的结果是：" + workerWrapper.getWorkResult());
//        logger.info("worker1 的结果是：" + workerWrapper1.getWorkResult());
//        logger.info("worker2 的结果是：" + workerWrapper2.getWorkResult());

        return "success!";
    }


}
